<?php
/**
 * Created by PhpStorm.
 * User: andy
 * Date: 2019/8/29
 * Time: 下午6:42
 */
namespace app\common\model;

use think\Model;
use think\facade\Cache;

class AdModel extends Model
{
    const STATUS_SHOW=1; //启用
    const STATUS_HIDE=0; //禁用

    protected $pk='ad_id'; //指定主键

    public function position()
    {
        return $this->hasOne('AdPositionModel','position_id','pid')->field('position_id,position_name');
    }

    /**
     * 所有分组
     * @param int $pageSum 每页显示条数
     * @param bool $status 是否需要分页
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getALL($pageSum=0)
    {
        if($pageSum<=0){
            $pageSum=getSystem("pageSUM")?getSystem("pageSUM"):10;
        }

        $list=self::where('ad_id','>',0)
            ->with('position')
            ->paginate($pageSum);

        return $list;
    }



    /**
     * 增加分组
     * @param $data
     * @return bool
     */
    public function adds($data){
        if(empty($data['ad_id'])){
            $data["start_time"]=strtotime($data["start_time"]);
            $data["end_time"]=strtotime($data["end_time"]);
            $status = self::save($data);

            if($status){
                return['status'=>1,'msg'=>'增加成功！'];
            }else{
                return['status'=>0,'msg'=>'增加失败！'];
            }
        }else{
            $data["start_time"]=strtotime($data["start_time"]);
            $data["end_time"]=strtotime($data["end_time"]);
            $status = self::save($data,['ad_id'=>$data["ad_id"]]);

            if($status){
                return['status'=>1,'msg'=>'修改成功！'];
            }else{
                return['status'=>0,'msg'=>'修改失败！'];
            }
        }

    }

    /**
     * 删除
     * @param $id
     * @return array
     */
    public function del($id){

        $status=self::destroy($id);
        if($status){
            return ['status'=>1,'msg'=>'删除成功！'];
        }else{
            return ['status'=>0,'msg'=>'删除失败！'];
        }

    }

    /**
     * 获取广告列表
     * @param $pid
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getAdList($pid){
        $adSum=getSystem("ad_numb")?getSystem("ad_numb"):5;

        $field="ad_id,ad_name,ad_link,thumb,start_time,end_time";
        $list=self::field($field)
            ->where('status',self::STATUS_SHOW)
            ->where('pid',$pid)
            ->where('start_time','<=',time())
            //->where('end_time','>=',time())
            ->order('list_order asc')
            ->limit($adSum)
            ->select();

        return $list;
    }

}